define(function(require, exports, module) {
    var Notify = require('common/bootstrap-notify');
    var Widget = require('widget');
    //require('jquery.plupload-queue-css');
    //require('jquery.plupload-queue');
    // 这里require是有顺序要求的

    //var VideoQualitySwitcher = require('../widget/video-quality-switcher');

    //引入七牛sdk
    require('../qiniu/js/jquery-1.9.1.min');
    require('../qiniu/bootstrap/js/bootstrap.min');
    require('../qiniu/js/plupload/plupload.full.min');
    require('../qiniu/js/plupload/i18n/zh_CN');
    require('../qiniu/js/qiniu');
    require('../qiniu/js/ui');
    require('../qiniu/js/qiniu');
    require('../qiniu/js/highlight/highlight.js');
    //require('../qiniu/js/main');

    var $div = $("#file-chooser-uploader-div");
    var divData = $div.data();
    console.log(divData.uptokenUrl);

    $.ajax({
        url: divData.uptokenUrl,
        async: false,
        dataType: 'json',
        cache: false,
        success: function(response, status, jqXHR) {
            console.log(response);
            /*var time = new Date().getTime();
            var $chars = 'abcdefhijkmnprstwxyz';
            var maxPos = $chars.length;
            var random = '';
            for (i = 0; i < 6; i++) {
            　　random += $chars.charAt(Math.floor(Math.random() * maxPos));
            }
            key = time+random;
            console.log(key);*/

            //设置自定义文件和可上传的格式
            var $container = $("#file-uploader-container"),
                    targetType = $container.data('targetType'),
                    uploadMode = $container.data('uploadMode'),
                    hlsEncrypted = $container.data('hlsEncrypted');

            var switcher = null;
            if ($('.quality-switcher').length > 0) {
                var switcher = new VideoQualitySwitcher({
                    element: '.quality-switcher'
                });
            }


            var extensions = '';
            if (targetType == 'courselesson') {
                if (uploadMode == 'cloud') {
                    extensions = 'mp3,mp4,avi,flv,wmv,mov,ppt,pptx,doc,docx,pdf,swf';
                } else {
                    extensions = 'mp3,mp4,avi,flv,wmv,mov,swf';
                }
            } else if (targetType == 'coursematerial') {
                extensions = 'jpg,jpeg,gif,png,txt,doc,docx,xls,xlsx,pdf,ppt,pptx,pps,ods,odp,mp4,mp3,avi,flv,wmv,wma,zip,rar,gz,tar,7z,swf';
            }

            var filters = [];
            if (extensions.length > 0) {
                filters = [{
                    title: "Files",
                    extensions: extensions
                }];
            }


            var uploader = Qiniu.uploader({
                runtimes: 'html5,flash,html4',
                browse_button: 'pickfiles',
                container: 'container',
                drop_element: 'container',
                max_file_size: '1024mb',
                flash_swf_url: 'js/plupload/Moxie.swf',
                dragdrop: true,
                chunk_size: '4mb',
                filters: filters,
                //uptoken_url: divData.uptokenUrl,
                uptoken: response.uptoken,
                domain: 'http://7xpf21.com2.z0.glb.qiniucdn.com/',//'http://7xpk3a.com2.z0.glb.qiniucdn.com/',
                get_new_uptoken: false,
                // downtoken_url: '/downtoken',
                // unique_names: true,
                // save_key: true,
                // x_vars: {
                //     'id': '1234',
                //     'time': function(up, file) {
                //         var time = (new Date()).getTime();
                //         // do something with 'time'
                //         return time;
                //     },
                // },
                auto_start: true,
                init: {
                    'FilesAdded': function(up, files) {
                        $('table').show();
                        $('#success').hide();
                        plupload.each(files, function(file) {
                            var progress = new FileProgress(file, 'fsUploadProgress');
                            progress.setStatus("等待...");
                            progress.bindUploadCancel(up);
                        });
                    },
                    'BeforeUpload': function(up, file) {
                        var progress = new FileProgress(file, 'fsUploadProgress');
                        var chunk_size = plupload.parseSize(this.getOption('chunk_size'));
                        if (up.runtime === 'html5' && chunk_size) {
                            progress.setChunkProgess(chunk_size);
                        }
                    },
                    'UploadProgress': function(up, file) {
                        var progress = new FileProgress(file, 'fsUploadProgress');
                        var chunk_size = plupload.parseSize(this.getOption('chunk_size'));
                        progress.setProgress(file.percent + "%", file.speed, chunk_size);
                    },
                    'UploadComplete': function() {
                        $('#success').show();
                    },
                    'FileUploaded': function(up, file, info) {
                        var progress = new FileProgress(file, 'fsUploadProgress');
                        var mp4FileName = 'http://7xpk3a.com2.z0.glb.qiniucdn.com/'+response.basename+'.mp4';
                        console.log(file);
                        //var data = $.parseJSON(file);
                        //console.log(data);
                        $.ajax({
                            url: divData.qiniuuploadUrl,
                            async: false,
                            dataType: 'json',
                            cache: false,
                            data: {file:JSON.stringify(file),qiniuname:response.basename},
                            success: function(response, status, jqXHR) {
                                console.log(response);
                            }
                        });
                        progress.setComplete(up, info, mp4FileName);

                    },
                    'Error': function(up, err, errTip) {
                        $('table').show();
                        var progress = new FileProgress(err.file, 'fsUploadProgress');
                        progress.setError();
                        progress.setStatus(errTip);
                    }
                        // ,
                        // 'Key': function(up, file) {
                        //     var key = "";
                        //     // do something with key
                        //     return key
                        // }
                }
            });

            uploader.bind('FileUploaded', function() {
                console.log('hello man,a file is uploaded');
            });
            $('#container').on(
                'dragenter',
                function(e) {
                    e.preventDefault();
                    $('#container').addClass('draging');
                    e.stopPropagation();
                }
            ).on('drop', function(e) {
                e.preventDefault();
                $('#container').removeClass('draging');
                e.stopPropagation();
            }).on('dragleave', function(e) {
                e.preventDefault();
                $('#container').removeClass('draging');
                e.stopPropagation();
            }).on('dragover', function(e) {
                e.preventDefault();
                $('#container').addClass('draging');
                e.stopPropagation();
            });



            $('#show_code').on('click', function() {
                $('#myModal-code').modal();
                $('pre code').each(function(i, e) {
                    hljs.highlightBlock(e);
                });
            });


            $('body').on('click', 'table button.btn', function() {
                $(this).parents('tr').next().toggle();
            });


            var getRotate = function(url) {
                if (!url) {
                    return 0;
                }
                var arr = url.split('/');
                for (var i = 0, len = arr.length; i < len; i++) {
                    if (arr[i] === 'rotate') {
                        return parseInt(arr[i + 1], 10);
                    }
                }
                return 0;
            };

            $('#myModal-img .modal-body-footer').find('a').on('click', function() {
                var img = $('#myModal-img').find('.modal-body img');
                var key = img.data('key');
                var oldUrl = img.attr('src');
                var originHeight = parseInt(img.data('h'), 10);
                var fopArr = [];
                var rotate = getRotate(oldUrl);
                if (!$(this).hasClass('no-disable-click')) {
                    $(this).addClass('disabled').siblings().removeClass('disabled');
                    if ($(this).data('imagemogr') !== 'no-rotate') {
                        fopArr.push({
                            'fop': 'imageMogr2',
                            'auto-orient': true,
                            'strip': true,
                            'rotate': rotate,
                            'format': 'png'
                        });
                    }
                } else {
                    $(this).siblings().removeClass('disabled');
                    var imageMogr = $(this).data('imagemogr');
                    if (imageMogr === 'left') {
                        rotate = rotate - 90 < 0 ? rotate + 270 : rotate - 90;
                    } else if (imageMogr === 'right') {
                        rotate = rotate + 90 > 360 ? rotate - 270 : rotate + 90;
                    }
                    fopArr.push({
                        'fop': 'imageMogr2',
                        'auto-orient': true,
                        'strip': true,
                        'rotate': rotate,
                        'format': 'png'
                    });
                }

                $('#myModal-img .modal-body-footer').find('a.disabled').each(function() {

                    var watermark = $(this).data('watermark');
                    var imageView = $(this).data('imageview');
                    var imageMogr = $(this).data('imagemogr');

                    if (watermark) {
                        fopArr.push({
                            fop: 'watermark',
                            mode: 1,
                            image: 'http://www.b1.qiniudn.com/images/logo-2.png',
                            dissolve: 100,
                            gravity: watermark,
                            dx: 100,
                            dy: 100
                        });
                    }

                    if (imageView) {
                        var height;
                        switch (imageView) {
                            case 'large':
                                height = originHeight;
                                break;
                            case 'middle':
                                height = originHeight * 0.5;
                                break;
                            case 'small':
                                height = originHeight * 0.1;
                                break;
                            default:
                                height = originHeight;
                                break;
                        }
                        fopArr.push({
                            fop: 'imageView2',
                            mode: 3,
                            h: parseInt(height, 10),
                            q: 100,
                            format: 'png'
                        });
                    }

                    if (imageMogr === 'no-rotate') {
                        fopArr.push({
                            'fop': 'imageMogr2',
                            'auto-orient': true,
                            'strip': true,
                            'rotate': 0,
                            'format': 'png'
                        });
                    }
                });

                var newUrl = Qiniu.pipeline(fopArr, key);

                var newImg = new Image();
                img.attr('src', 'loading.gif');
                newImg.onload = function() {
                    img.attr('src', newUrl);
                    img.parent('a').attr('href', newUrl);
                };
                newImg.src = newUrl;
                return false;
            });
        },
        error: function(jqXHR, status, error) {
            console.log(error);
            Notify.danger('请求上传授权码失败！');
            up.stop();
        }
    });

    

    // domain 为七牛空间（bucket)对应的域名，选择某个空间后，可通过"空间设置->基本设置->域名设置"查看获取

    // uploader 为一个plupload对象，继承了所有plupload的方法，参考http://plupload.com/docs

    $('#modal').on('hide.bs.modal', function(e) {
        var uploader = $div.pluploadQueue();
            
        if (uploader.files.length > 0 && (uploader.total.uploaded != (uploader.files.length - uploader.total.failed))) {
                
            if (!confirm('当前正在上传的文件将停止上传，确定关闭？')) {
                return false;
            }
        }

            
        window.location.reload();
    });

    
});